<template>
  <div>
    <!-- 查询表单 -->
    <el-form style="margin-left: 5px;margin-top: 10px;" :model="queryParams" label-position="right" :inline="true"
      ref="queryRef" v-show="showSearch">

      <el-form-item :label="$t('produce.cksspotcheckPage.page.batchCode')" prop="batchCode">
        <el-input v-model="queryParams.batchCode" :placeholder="$t('produce.cksspotcheckPage.page.batchCodeInput')"
          clearable @keyup.enter="handleQuery" style="width: 230px" />
      </el-form-item>

      <el-form-item :label="$t('produce.cksspotcheckPage.page.primaryCode')" prop="primaryCode">
        <el-input v-model="queryParams.primaryCode" :placeholder="$t('produce.cksspotcheckPage.page.primaryCodeInput')"
          clearable @keyup.enter="handleQuery" style="width: 230px" />
      </el-form-item>

      <el-form-item :label="$t('produce.cksspotcheckPage.page.createdTime')" prop="dateRange">
        <el-date-picker style="width: 360px" v-model="queryParams.dateRange" type="datetimerange"
          :default-time="defaultTime" :shortcuts="shortcuts" value-format="YYYY-MM-DD HH:mm:ss" range-separator="-" />
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button icon="search" type="primary" @click="handleQuery">{{ $t('btn.search') }}</el-button>
        <el-button icon="refresh" @click="resetQuery">{{ $t('btn.reset') }}</el-button>

      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="15" class="mb10">
      <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar> -->
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdateData"
          v-hasPermi="['produce:cksspotcheck:remove']">
          {{ $t('btn.edit') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleRemoveData"
          v-hasPermi="['produce:cksspotcheck:edit']">
          {{ $t('btn.delete') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="upload.open = true"
          v-hasPermi="['produce:cksspotcheck:import']">
          {{ $t('btn.import') }}
        </el-button>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-table :data="dataList" v-loading="loading" ref="table" border header-cell-class-name="el-table-header-cell"
      highlight-current-row style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40" />
      <el-table-column v-for="col in columns.filter(o => o.visible)" :key="col.prop" :prop="col.prop"
        :label="$t('produce.cksspotcheckPage.tableColumns.' + col.prop)" align="center" :width="col.width || 'auto'"
        :show-overflow-tooltip="true">
        <!-- 产品类型 -->
        <template #default="scope" v-if="col.prop == 'type'">
          <el-tag v-if="scope.row.type !== null" :type="scope.row.type === 1 ? 'success' : 'danger'"
            disable-transitions>
            <div style="display: flex;align-items: center;justify-items: center;">
              <span>{{ scope.row.type === 1 ? $t('produce.cksspotcheckPage.formDialog.ok') :
                $t('produce.cksspotcheckPage.formDialog.ng') }}</span>
            </div>
          </el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />


    <!-- 用户导入对话框 -->
    <el-dialog :title="$t('produce.cksspotcheckPage.importDialog.importTitle')" v-model="upload.open" width="600px"
      append-to-body>
      <el-upload name="file" ref="uploadRef" :limit="1" accept=".xlsx,.xls" :headers="upload.headers"
        :action="upload.url" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">{{ $t('produce.cksspotcheckPage.importDialog.uploadText') }}</div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>{{ $t('produce.cksspotcheckPage.importDialog.uploadTip') }}</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate">{{ $t('produce.cksspotcheckPage.importDialog.downloadTemplate') }}</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <el-button @click="upload.open = false">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" @click="submitFileForm">{{ $t('btn.submit') }}</el-button>
      </template>
    </el-dialog>

    <!-- 修改信息对话框 -->
    <el-dialog :title="$t('produce.cksspotcheckPage.formDialog.editTitle')" v-model="editDialogVisible" width="800px"
      append-to-body>
      <el-form ref="editFormRef" :model="editForm" label-width="100px">
        <el-form-item :label="$t('produce.cksspotcheckPage.formDialog.spotCheckId')" prop="spotCheckId">
          <el-input v-model="editForm.spotCheckId"
            :placeholder="$t('produce.cksspotcheckPage.formDialog.spotCheckIdInput')" disabled style="width: 200px" />
        </el-form-item>
        <el-form-item :label="$t('produce.cksspotcheckPage.page.batchCode')" prop="batchCode">
          <el-input v-model="editForm.batchCode" :placeholder="$t('produce.cksspotcheckPage.page.batchCodeInput')"
            clearable style="width: 200px" />
        </el-form-item>
        <el-form-item :label="$t('produce.cksspotcheckPage.page.primaryCode')" prop="primaryCode">
          <el-input v-model="editForm.primaryCode" :placeholder="$t('produce.cksspotcheckPage.page.primaryCodeInput')"
            clearable style="width: 200px" />
        </el-form-item>
        <el-form-item :label="$t('produce.cksspotcheckPage.tableColumns.type')" prop="type">
          <el-select v-model="editForm.type" :placeholder="$t('produce.cksspotcheckPage.formDialog.type')" clearable
            style="width: 200px">
            <el-option :label="$t('produce.cksspotcheckPage.formDialog.ok')" :value="1"></el-option>
            <el-option :label="$t('produce.cksspotcheckPage.formDialog.ng')" :value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" @click="submitEditForm">{{ $t('btn.submit') }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="cksspotcheck">
import { getToken } from '@/utils/auth'
import { listCksSpotCheck, deleteCksSpotCheck, updateCksSpotCheck } from '@/api/business/cksspotcheck.js'
import dayjs from 'dayjs'

const { proxy } = getCurrentInstance()
const defaultTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])
const loading = ref(false)
const showSearch = ref(true)
const today = dayjs()
const table = ref(null)
const single = ref(true)
const multiple = ref(true)

// 时间范围快捷选项
const shortcuts = [
  {
    text: proxy.$t('common.today'),
    value: () => {
      const start = new Date().setHours(0, 0, 0, 0)
      const end = new Date().setHours(23, 59, 59, 999)
      return [start, end]
    },
  },
  {
    text: proxy.$t('common.thisWeek'),
    value: () => {
      const start = new Date()
      const end = new Date().setHours(23, 59, 59, 999)
      start.setHours(0, 0, 0, 0)
      start.setDate(start.getDate() - 7)
      return [start, end]
    },
  },
  {
    text: proxy.$t('common.thisMonth'),
    value: () => {
      const start = new Date()
      const end = new Date().setHours(23, 59, 59, 999)
      start.setHours(0, 0, 0, 0)
      start.setMonth(start.getMonth() - 1)
      return [start, end]
    },
  },
  {
    text: proxy.$t('common.last3Month'),
    value: () => {
      const start = new Date()
      const end = new Date().setHours(23, 59, 59, 999)
      start.setHours(0, 0, 0, 0)
      start.setMonth(start.getMonth() - 3)
      return [start, end]
    },
  },
]

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  batchCode: '',
  primaryCode: '',
  dateRange: [today.startOf('day').format('YYYY-MM-DD HH:mm:ss'), today.endOf('day').format('YYYY-MM-DD HH:mm:ss')],
})

const upload = reactive({
  open: false,
  title: proxy.$t('produce.cksspotcheckPage.importDialog.importTitle'),
  isUploading: false,
  updateSupport: 0,
  headers: { Authorization: 'Bearer ' + getToken() },
  url: import.meta.env.VITE_APP_BASE_API + '/business/CksSpotCheck/importData'
})

const columns = ref([
  { visible: true, prop: 'spotCheckId', label: proxy.$t('produce.cksspotcheckPage.tableColumns.spotCheckId'), width: '100' },
  { visible: true, prop: 'batchCode', label: proxy.$t('produce.cksspotcheckPage.tableColumns.batchCode'), width: '0' },
  { visible: true, prop: 'primaryCode', label: proxy.$t('produce.cksspotcheckPage.tableColumns.primaryCode') },
  { visible: true, prop: 'type', label: proxy.$t('produce.cksspotcheckPage.tableColumns.type'), width: '' },
  { visible: true, prop: 'creator', label: proxy.$t('produce.cksspotcheckPage.tableColumns.creator'), width: '' },
  { visible: true, prop: 'createdTime', label: proxy.$t('produce.cksspotcheckPage.tableColumns.createdTime'), width: '' },
])

const total = ref(0)
const dataList = ref([])

const editDialogVisible = ref(false);
const editForm = reactive({
  spotCheckId: null,
  batchCode: '',
  primaryCode: '',
  type: null,
});

function getList() {
  loading.value = true
  const formBody = JSON.parse(JSON.stringify(queryParams));
  proxy.addDateRange(formBody, queryParams.dateRange);
  delete formBody.dateRange;
  listCksSpotCheck(formBody).then(res => {
    const { code, data } = res
    if (code === 200) {
      dataList.value = data.result
      total.value = data.totalNum
    }
    loading.value = false
  })
}

function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

function handleSelectionChange(selection) {
  single.value = selection.length != 1
  multiple.value = !selection.length
}

function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download('/business/CksSpotCheck/downloadExportTemplate', proxy.$t('produce.cksspotcheckPage.importDialog.downloadTemplateFileName'))
}

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs['uploadRef'].submit()
}

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  const { code, msg, data } = response
  upload.open = false
  upload.isUploading = false
  proxy.$refs['uploadRef'].clearFiles()
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + data.item1 + '</div>', proxy.$t('produce.cksspotcheckPage.importDialog.importResultTitle'), {
    dangerouslyUseHTMLString: true
  })
  getList()
}

function handleRemoveData() {
  if (proxy.$refs.table) {
    const selectedRows = proxy.$refs.table.getSelectionRows();
    if (selectedRows.length === 0) {
      proxy.$modal.msgWarning(proxy.$t('produce.cksspotcheckPage.operateTips.deleteSelectTip'), 'warning');
      return;
    }
    proxy.$modal.confirm(proxy.$t('produce.cksspotcheckPage.operateTips.deleteConfirm', { count: selectedRows.length }), proxy.$t('btn.confirm'), {
      type: 'warning'
    }).then(() => {
      deleteCksSpotCheck(selectedRows.map(row => row.spotCheckId)).then(res => {
        const { code, msg, data } = res;
        if (code === 200 && msg == 'success') {
          getList();
        } else {
          proxy.$modal.msgError(proxy.$t('produce.cksspotcheckPage.operateTips.deleteFail', { errorMsg: data?.errorMsg || '' }));
        }
      })
    })
  }
}

function handleUpdateData() {
  if (proxy.$refs.table) {
    const selectedRows = proxy.$refs.table.getSelectionRows();
    if (selectedRows.length === 0) {
      proxy.$modal.msgWarning(proxy.$t('produce.cksspotcheckPage.operateTips.updateSelectTip'), 'warning');
      return;
    }
    if (selectedRows.length > 1) {
      proxy.$modal.msgWarning(proxy.$t('produce.cksspotcheckPage.operateTips.updateOnlyOneTip'), 'warning');
      return;
    }
    const row = selectedRows[0];
    editForm.spotCheckId = row.spotCheckId;
    editForm.batchCode = row.batchCode;
    editForm.primaryCode = row.primaryCode;
    editForm.type = row.type;
    editDialogVisible.value = true;
  }
}

function submitEditForm() {
  updateCksSpotCheck(editForm).then(res => {
    const { code, msg } = res;
    if (code === 200 && msg == 'success') {
      editDialogVisible.value = false;
      getList();
    } else {
      proxy.$modal.msgError(msg);
    }
  })
}

handleQuery()
</script>